package top.szhome.framework.starter.auth.util;

import io.jsonwebtoken.Claims;
import top.szhome.framework.core.tools.constant.AuthConstant;
import top.szhome.framework.core.tools.util.WebUtil;
import top.szhome.framework.starter.auth.AuthContext;
import top.szhome.framework.starter.jwt.JwtUtil;

/**
 * 认证工具类
 *
 * @author 唐加利
 * @date 2023/7/24
 **/
public class AuthUtil {

    private static final String REQUEST_ATTR_AUTH_CONTEXT = "REQUEST_ATTR_AUTH_CONTEXT";

    /**
     * 获取当前登录用户信息
     * @return
     */
    public static AuthContext getContext() {
        AuthContext context = WebUtil.getRequestAttr(REQUEST_ATTR_AUTH_CONTEXT);
        if(context == null){
            String auth = getToken();
            Claims claims = JwtUtil.parseJWT(auth);
            context = buildAuthContext(claims);
            if(context == null){
                context = new AuthContext();
                context.setUserId(1686266204953571330L);
                context.setTenantId("000000");
                context.setUsername("admin");
            }
            WebUtil.setRequestAttr(REQUEST_ATTR_AUTH_CONTEXT, context);
        }
        return context;
    }

    /**
     * 构建认证上下文
     * @param claims
     * @return
     */
    private static AuthContext buildAuthContext(Claims claims) {
//        if(claims == null){
//            return null;
//        }

        AuthContext context = new AuthContext();
        context.setUserId(1686266204953571330L);
        context.setUsername("admin");
        context.setTenantId("000000");
        return context;
    }

    /**
     * 获取Token信息，优先级：Header -> Cookie -> Parameter
     * @return
     */
    private static String getToken(){
        String auth = WebUtil.getHeader(AuthConstant.AUTH_TOKEN_HEADER);
        if(auth != null){
            return auth;
        }

        auth = WebUtil.getCookie(AuthConstant.AUTH_TOKEN_HEADER);
        if(auth != null){
            return auth;
        }

        return WebUtil.getParam(AuthConstant.AUTH_TOKEN_HEADER);
    }

}
